os.loadAPI("/System/API/image")
os.loadAPI("/System/API/windows")
os.loadAPI("/System/API/context")

local Args = {...}
local run = true
local xSize, ySize = term.getSize()
local xCenter, yCenter = math.floor(xSize/2)+1, math.floor(ySize/2)+1
local screen = 1
local maxScreen = 1
local file = {}
local intro = "No images"
local bars = true
local view = false
local posScroll = 0
local step = 0
local folders = {}
local sizeX = 0
local albums = 0
local pos = 0
local obj = {}

if #Args>0 or version<'5.1.2' then
	view = true
end

local newObj = function(name,x1,y1,x2,y2)
 obj[name] = {}
 obj[name]["x1"] = x1
 obj[name]["y1"] = y1
 obj[name]["x2"] = x2
 obj[name]["y2"] = y2
end

local startPath = Args[1]
if startPath == nil then
	startPath = "/Images"
end

local clear = function(color)
	term.setBackgroundColor(color)
	term.clear()
	term.setCursorPos(1,1)
end

local usualText = function(string,xPos,yPos)
	term.setCursorPos(xPos,yPos)
	term.write(string)
end

local function fadeIn(time)
    clear(colors.gray)
    sleep(time)
    clear(colors.lightGray)
    sleep(time)
    clear(colors.white)
    sleep(time)
end

local function fadeOut(time)
    clear(colors.lightGray)
    sleep(time)
    clear(colors.gray)
    sleep(time)
    clear(colors.black)
    sleep(time)
    term.setCursorPos(1,1)
    term.setTextColor(colors.white)
end

local sysBar = function()
	sysbar.header('ImageViewer',colors.white,colors.black)
	term.setTextColor(colors.lightGray)
	if view and file[screen]~=nil then
		usualText(startPath.."/"..file[screen],1,2)
	end
	sysbar.draw(colors.black,colors.white,noty,true,view)
end

local function scan(path)
	local f = fs.list(path)
	local find = false
	for i=1,#f do
		if windows.getFileFormat(path..'/'..f[i]) == '.png' and find == false then
			folders[#folders+1] = path
			find = true
		elseif fs.isDir(path..'/'..f[i]) and windows.getFileFormat(f[i]) ~= '.apk' then
			scan(path..'/'..f[i])
		end
	end
end

local function findFold(text)
	local pos = string.find(text,'/')
	while pos ~= nil do
		text = string.sub(text,pos+1)
		pos = string.find(text,'/')
	end
	if #text > 7 then
		text = ".."..string.sub(text,#text-4)
	end
	return text
end

local redraw = function()
	if view then
		if Args[2] == nil then
			local files = fs.list(startPath)
			local b = 1
			file = {}
			for i=1,#files do
				local fileFormat = windows.getFileFormat(files[i])
				if fileFormat == ".png" then
					file[b] = files[i]
					b=b+1
				end
			end
		else
			file[1] = Args[2]
		end
		clear(colors.black)
		if #file == 0 then
			term.setTextColor(colors.white)
			usualText(intro,xCenter-(#intro/2)+1,yCenter)
			sysBar()
		else
			maxScreen = #file
			local path = startPath.."/"..file[screen]
			local img = fs.open(path,'r')
			local line = img.readLine()
			local maxLine = 0
			local ys = 0
			while line ~= nil do
				if #line > maxLine then
					maxLine = #line
				end
				line = img.readLine()
				ys = ys + 1
			end
			image.draw(xCenter-math.floor((maxLine/3)/2),yCenter-math.floor(ys/2),path)
			if bars then
				term.setTextColor(colors.white)
				if screen > 1 then
					paintutils.drawLine(1,yCenter-1,1,yCenter+1,colors.black)
					usualText("<",1,yCenter)
				end
				if screen < maxScreen then
					paintutils.drawLine(xSize,yCenter-1,xSize,yCenter+1,colors.black)
					usualText(">",xSize,yCenter)
				end
				sysBar()
			end
		end
	else
		folders = {}
		scan('/')
		clear(colors.black)
		sizeX = math.floor(xSize/8)
		local num = 1
		albums = math.ceil(#folders/sizeX)
		for i=1,albums do
			if #folders<sizeX then sizeX = #folders end
				for ii=1,sizeX do
					if num<#folders then
					local f = fs.list(folders[num])
					for g=1,#f do
						if windows.getFileFormat(folders[num]..'/'..f[g]) == '.png' then
							paintutils.drawFilledBox(ii*8-7,i*6-3+pos,ii*8-1,i*6+1+pos,colors.gray)
							image.draw(ii*8-7,i*6-3+pos,folders[num]..'/'..f[g],7,4)
							term.setBackgroundColor(colors.gray)
							term.setTextColor(colors.white)
							usualText(findFold(folders[num]),ii*8-7,i*6+1+pos)
							newObj(folders[num],ii*8-7,i*6-3+pos,ii*8-1,i*6+1+pos)
							num = num + 1
							break
						end
					end
				end
			end
		end
		step = sysbar.scrollBar(albums,6,posScroll,1.5,colors.gray,colors.black)
		sysBar()
	end
end

local running = function()
 while run do
  event, side, x, y = os.pullEvent()
  if event == "mouse_click" then
   if view then
    if x==xSize and y<ySize and y>2 and screen < maxScreen then 
     screen = screen+1
	 paintutils.drawLine(xSize,yCenter-1,xSize,yCenter+1,colors.lightGray)
 	 usualText(">",xSize,yCenter)
	 sleep(0.1)
     redraw()
    elseif x==1 and y<ySize and y>2 and screen > 1 then 
     screen = screen-1
 	 paintutils.drawLine(1,yCenter-1,1,yCenter+1,colors.lightGray)
	 usualText("<",1,yCenter)
	 sleep(0.1)
     redraw()
    elseif x==xSize and y==ySize and #file > 0 then
     term.setBackgroundColor(colors.gray)
     term.setTextColor(colors.lightGray)
     usualText("|",xSize,ySize)
 	 local budka = contexts.main(xSize,ySize-1,'Account picture','Set Wallpapers','Delete')
	 if budka == 'Account picture' then
	  if log == false then shell.run("/ver") end
      local f = fs.list("/System")
      for I=1,#f do
       if f[I]==l_login..".png" then
        shell.run("rm /System/"..l_login..".png")
       end
      end
      shell.run("copy "..startPath.."/"..file[screen].." /System/"..l_login..".png")
	 elseif budka == 'Set Wallpapers' then
	  local f = fs.list("/System")
      for I=1,#f do
       if f[I]=="wallp.png" then
        shell.run("rm /System/wallp.png")
       end
      end
      shell.run("copy "..startPath.."/"..file[screen].." /System/wallp.png")
	 elseif budka == 'Delete' then
	  shell.run("rm "..startPath.."/"..file[screen])
      local files = fs.list(startPath)
      b=1
      for i=1,#files do
       local fileFormat = windows.getFileFormat(files[i])
       if fileFormat == ".png" then
        file[b] = files[i]
        b=b+1
       end
      end
	 end
	 redraw()
    elseif bars and not sysbar.back(x,y) then
     bars = false
 	 redraw()
    elseif bars == false and not sysbar.back(x,y) then
     bars = true
	 redraw()
    end
   elseif view == false then
	if y>2 and y<ySize then
     for i=1,#folders-1 do
	  if x>=obj[folders[i]]["x1"] and x<=obj[folders[i]]["x2"] and y>=obj[folders[i]]["y1"] and y<=obj[folders[i]]["y2"] and y<ySize then
	   if side == 1 then
	    startPath = folders[i]
	    view = true
	    break
	   elseif side == 2 then
	    local budka = contexts.main(x,y,'Delete')
	    if budka == 'Delete' then
		 redraw()
		 local ot = windows.select({"Delete album"},{"Are you sure?"},{"Yes",colors.red,colors.white},{"No",colors.gray,colors.white})
		 if ot == 'Yes' then
	      local error = shell.run("rm "..folders[i])
		  if error ~= nil then
		   windows.error(error)
		  end
		 end
		 redraw()
		 break
		end
	   end
	  end
	 end
	 redraw()
	end
   end
   if sysbar.back(x,y) then
    if view and version >= '5.1.2' and Args[1]==nil then
	 screen = 1
	 view = false
	 redraw()
	else
     term.clear()
     term.setCursorPos(1,1)
     run = false
	end
   elseif sysbar.home(x,y) then
    term.clear()
    term.setCursorPos(1,1)
    run = false
    home = true
   end
  elseif event == "mouse_scroll" and view == false then
   if albums*6>ySize-3 then
    if side == 1 then
     if pos>-albums*6+ySize-3 then
      posScroll = posScroll-step
      pos = pos-1
     else
      pos = -albums*6+ySize-3
     end 
    elseif side == -1 then
     if pos<0 then 
      pos = pos+1
      posScroll = posScroll+step
     else
      pos = 0
     end
    end
    redraw()
   end
  end
 end
end

fadeIn(0)
redraw()
running()
fadeOut(0)